package com.photologics.logic;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.widget.GridLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.photologics.logic.LogicHelper.coinGiveType;
import com.photologics.logic.LogicHelper.item;
import com.photologics.logic.LogicHelper.tileState;
import com.photologics.main.GiveCoinDialog;
import com.photologics.main.R;

public class LogicActivity extends Activity implements OnTouchListener {
	final static String TAG = "LogicActivity";
	final static int LUCKY_PERCENT = 30;
	final int THIN_LINE = 2;
	final int THICK_LINE = 7;

	private static ScrollView verticalScroll, verticalHintScroll,
			verticalDivideTileScroll;
	private static HorizontalScrollView horizontalScroll, horizontalHintScroll,
			horizontalDivideTileScroll;
	private static ImageView verticalHintImage, mapView, touchBoard;
	private static ImageView verticalDivideTile, horizontalDivideTile;
	private static FrameLayout logicFrame;
	private LinearLayout logicInfoBoard;
	private static GridLayout logicBoard, verticalHintBoard,
			horizontalHintBoard, failCheckBoard;
	private static ChangeLogic changeLogic;
	private static ImageView[][] tile;
	private static ImageView[] failCheck;
	private static TextView[][] verticalHint, horizontalHint;
	private static ImageButton moveBtn, editBtn, itemBox;

	private static byte[][] logicValue, logicState;
	private byte[][] verticalHintValue, horizontalHintValue;
	private PointF first;
	private static Point drag, section, squar;
	private Point current;
	private static boolean moveFlag;
	private static boolean dialogOpen = false, firstTouchInCheck;
	private float previousDistance = 0, presentDistance;
	private static float scale = 1;
	private static int lcdWidth;
	private int lcdHeight;
	private static int verticalHintSize, horizontalHintSize;
	private static int verticalHintWidth;
	private static int numOfSuccess, successCount, failCount;
	private static Context context;
	private int dragCount = 0;
	private LogicHelper.dragStyle dir;
	private long Basetime;
	private static Chronometer timer;
	private static LogicHelper.item useItem;

	@Override
	@SuppressWarnings("deprecation")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_logic);

		lcdWidth = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getWidth();
		lcdHeight = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getHeight();

		drag = new Point(-1, -1);
		squar = new Point();
		current = new Point();
		first = new PointF();
		context = LogicActivity.this;

		changeLogic = new ChangeLogic();

		logicInfoBoard = (LinearLayout) findViewById(R.id.logic_info_board);

		failCheckBoard = (GridLayout) findViewById(R.id.fail_check_board);
		failCheck = new ImageView[5];
		for (int i = 0; i < 5; i++) {
			failCheck[i] = new ImageView(this);
			failCheck[i].setImageResource(R.drawable.fail_image);
			failCheckBoard.addView(failCheck[i]);
		}

		touchBoard = (ImageView) findViewById(R.id.touch_board);
		touchBoard.getLayoutParams().width = lcdWidth;
		touchBoard.getLayoutParams().height = lcdHeight;
		touchBoard.setOnTouchListener(this);

		verticalDivideTile = (ImageView) findViewById(R.id.vertical_Didve_5tile);
		horizontalDivideTile = (ImageView) findViewById(R.id.horizontal_Didve_5tile);

		horizontalDivideTileScroll = (HorizontalScrollView) findViewById(R.id.horizontal_Didve_5tile_scroll);
		verticalDivideTileScroll = (ScrollView) findViewById(R.id.vertical_Didve_5tile_scroll);
		verticalScroll = (ScrollView) findViewById(R.id.vertical_scroll_view);
		verticalHintScroll = (ScrollView) findViewById(R.id.verticalHintScrollView);
		horizontalScroll = (HorizontalScrollView) findViewById(R.id.horizontal_scroll_view);
		horizontalHintScroll = (HorizontalScrollView) findViewById(R.id.horizontal_hint_scroll_view);

		moveBtn = (ImageButton) findViewById(R.id.button_move);
		moveBtn.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				moveFlag = true;
				moveBtn.setImageResource(R.drawable.move_button_touched);
				editBtn.setImageResource(R.drawable.edit_button);
			}
		});
		editBtn = (ImageButton) findViewById(R.id.button_edit);

		editBtn.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				moveFlag = false;
				moveBtn.setImageResource(R.drawable.move_button);
				editBtn.setImageResource(R.drawable.edit_button_touched);
			}
		});
		moveFlag = true;

		itemBox = (ImageButton) findViewById(R.id.item_box);
		itemBox.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!dialogOpen) {
					if (useItem == item.NONE) {
						ItemUseDialog iuDialog = new ItemUseDialog(context);
						iuDialog.getWindow().clearFlags(
								WindowManager.LayoutParams.FLAG_DIM_BEHIND);

						WindowManager.LayoutParams params = iuDialog
								.getWindow().getAttributes();
						params.x = (params.width / 2 - lcdWidth / 2) + 165;
						params.y = (params.height / 2 - lcdHeight / 2) + 220;
						iuDialog.getWindow().setAttributes(params);

						iuDialog.show();
					} else {
						useItem = item.NONE;
						itemBox.setImageResource(R.drawable.item_none);
					}
				}
			}

		});

		useItem = item.NONE;

		new Thread(new Runnable() {

			@Override
			public void run() {
				Basetime = LogicHelper.db.getTime(LogicHelper.logicInfo
						.getName());
				timer = (Chronometer) findViewById(R.id.timer_view);
				timer.setBase(SystemClock.elapsedRealtime() - Basetime);
				timer.start();

			}
		}).start();
		Log.i(TAG, "start");

		createLogic();

		creatHint();

		scroll(1, 1);
	}

	private void createLogic() {
		logicBoard = (GridLayout) findViewById(R.id.logic_board);
		logicFrame = (FrameLayout) findViewById(R.id.logic_frame);
		verticalHintImage = (ImageView) findViewById(R.id.vertical_hint_image);
		mapView = (ImageView) findViewById(R.id.map_view);

		tile = new ImageView[LogicHelper.LOGIC_MAXSIZE][LogicHelper.LOGIC_MAXSIZE];

		section = LogicHelper.currentSection;

		logicValue = changeLogic.getLogicValue(section.x, section.y);
		logicState = changeLogic.getState(section.x, section.y);
		numOfSuccess = changeLogic.getNumOfSuccess();
		successCount = 0;
		failCount = 0;

		for (int i = 0; i < LogicHelper.LOGIC_MAXSIZE; i++) {
			for (int j = 0; j < LogicHelper.LOGIC_MAXSIZE; j++) {

				tile[i][j] = new ImageView(this);
				if (logicState[i][j] == 0) {
					tile[i][j].setImageResource(R.drawable.white_tile);
					tile[i][j].setContentDescription("BLANK");
				} else if (logicState[i][j] == 1) {
					tile[i][j].setImageResource(R.drawable.black_x_tile);
					tile[i][j].setContentDescription("CHECK");
				} else if (logicState[i][j] == 2) {
					tile[i][j].setImageResource(R.drawable.red_x_tile);
					tile[i][j].setContentDescription("FAIL");
					failCount++;
					checkFail();
				} else {
					tile[i][j].setImageResource(R.drawable.black_tile);
					tile[i][j].setContentDescription("SUCCESS");
					successCount++;
				}

				tile[i][j].setTag(i + "," + j);

				int leftPadding = THIN_LINE, topPadding = THIN_LINE, rightPadding = THIN_LINE, bottomPadding = THIN_LINE;
				if (i == 0)
					topPadding = THICK_LINE;
				if (j == 0)
					leftPadding = THICK_LINE;
				if ((i + 1) % 5 == 0)
					bottomPadding = THICK_LINE;
				if ((j + 1) % 5 == 0)
					rightPadding = THICK_LINE;
				tile[i][j].setPadding(leftPadding, topPadding, rightPadding,
						bottomPadding);

				logicBoard.addView(tile[i][j]);
			}
		}
	}

	private static void checkFail() {
		if (failCount >= 5) {
			LogicHelper.db.setZero(LogicHelper.logicInfo.getName(), section);
			finishSection();
		}
		for (int i = 4; i >= 0; i--) {
			if ((4 - i) < failCount)
				failCheck[i].setImageResource(R.drawable.fail_image_counted);
			else
				failCheck[i].setImageResource(R.drawable.fail_image);
		}
	}

	public static int getFailCount() {
		return failCount;
	}

	private void creatHint() {
		verticalHintBoard = (GridLayout) findViewById(R.id.vertical_hint_board);
		horizontalHintBoard = (GridLayout) findViewById(R.id.horizontal_hint_board);

		verticalHintValue = changeLogic.getVerticalHint();
		horizontalHintValue = changeLogic.getHorizontalHint();

		verticalHintSize = changeLogic.getVerticalHintSize();
		horizontalHintSize = changeLogic.getHorizontalHintSize();

		verticalHintBoard.setColumnCount(verticalHintSize);
		horizontalHintBoard.setRowCount(horizontalHintSize);

		verticalHint = new TextView[LogicHelper.LOGIC_MAXSIZE][verticalHintSize];
		horizontalHint = new TextView[horizontalHintSize][LogicHelper.LOGIC_MAXSIZE];

		BitmapDrawable bd = (BitmapDrawable) this.getResources().getDrawable(
				R.drawable.white_tile);

		verticalHintWidth = bd.getBitmap().getWidth() * verticalHintSize;

		horizontalDivideTile.setPadding(verticalHintWidth, 0, 0, 0);

		LinearLayout.LayoutParams plControl = (LinearLayout.LayoutParams) verticalHintImage
				.getLayoutParams();
		plControl.width = verticalHintWidth;
		verticalHintImage.setLayoutParams(plControl);

		plControl = (LinearLayout.LayoutParams) mapView.getLayoutParams();
		plControl.width = verticalHintWidth;
		mapView.setLayoutParams(plControl);

		for (int i = 0; i < LogicHelper.LOGIC_MAXSIZE; i++) {
			int numCount = 0;
			for (int j = 0; j < verticalHintSize; j++) {
				verticalHint[i][verticalHintSize - 1 - j] = new TextView(this);
				if (verticalHintValue[i][j] == 0) {
					if (j == 0) {
						verticalHint[i][verticalHintSize - 1 - j].setText("0");
						verticalHint[i][verticalHintSize - 1 - j].setTag("0");
						verticalHint[i][verticalHintSize - 1 - j]
								.setTextColor(Color.RED);
					} else {
						verticalHint[i][verticalHintSize - 1 - j].setText(" ");
						verticalHint[i][verticalHintSize - 1 - j].setTag(" ");
					}
				} else {
					numCount = j;
					verticalHint[i][verticalHintSize - 1 - j].setText(Byte
							.toString(verticalHintValue[i][j]));
					verticalHint[i][verticalHintSize - 1 - j].setTag(Byte
							.toString(verticalHintValue[i][j]));
				}
				verticalHint[i][verticalHintSize - 1 - j].setTextSize(20);
				verticalHint[i][verticalHintSize - 1 - j].setTypeface(null,
						Typeface.BOLD);
				verticalHint[i][verticalHintSize - 1 - j]
						.setGravity(Gravity.CENTER);
				if ((i + 1) % 5 == 0)
					verticalHint[i][verticalHintSize - 1 - j].setHeight(bd
							.getBitmap().getHeight() + THICK_LINE + THIN_LINE);
				else if (i == 0)
					verticalHint[i][verticalHintSize - 1 - j].setHeight(bd
							.getBitmap().getHeight() + THICK_LINE + THIN_LINE);
				else
					verticalHint[i][verticalHintSize - 1 - j].setHeight(bd
							.getBitmap().getHeight() + THIN_LINE * 2);
				verticalHint[i][verticalHintSize - 1 - j].setWidth((bd
						.getBitmap().getWidth()));
			}
			verticalHint[i][0].setContentDescription(Integer
					.toString(verticalHintSize - numCount - 1));
		}

		for (int i = 0; i < LogicHelper.LOGIC_MAXSIZE; i++) {
			for (int j = 0; j < horizontalHintSize; j++) {
				horizontalHint[horizontalHintSize - j - 1][i] = new TextView(
						this);
				if (horizontalHintValue[j][i] == 0) {
					if (j == 0) {
						horizontalHint[horizontalHintSize - j - 1][i]
								.setText("0");
						horizontalHint[horizontalHintSize - j - 1][i]
								.setTextColor(Color.RED);
					} else
						horizontalHint[horizontalHintSize - j - 1][i]
								.setText(" ");
				} else
					horizontalHint[horizontalHintSize - j - 1][i].setText(Byte
							.toString(horizontalHintValue[j][i]));
				horizontalHint[horizontalHintSize - j - 1][i].setTextSize(20);
				horizontalHint[horizontalHintSize - j - 1][i].setTypeface(null,
						Typeface.BOLD);
				horizontalHint[horizontalHintSize - j - 1][i]
						.setGravity(Gravity.CENTER);
				if ((i + 1) % 5 == 0)
					horizontalHint[horizontalHintSize - j - 1][i].setWidth(bd
							.getBitmap().getWidth() + THICK_LINE + THIN_LINE);
				else if (i == 0)
					horizontalHint[horizontalHintSize - j - 1][i].setWidth(bd
							.getBitmap().getWidth() + THICK_LINE + THIN_LINE);
				else
					horizontalHint[horizontalHintSize - j - 1][i].setWidth(bd
							.getBitmap().getWidth() + THIN_LINE * 2);
				horizontalHint[horizontalHintSize - j - 1][i]
						.setHeight((int) (bd.getBitmap().getHeight() * 0.8));
			}
		}

		for (int i = 0; i < LogicHelper.LOGIC_MAXSIZE; i++)
			for (int j = 0; j < verticalHintSize; j++)
				verticalHintBoard.addView(verticalHint[i][j],
						(i * verticalHintSize) + j);

		for (int i = 0; i < horizontalHintSize; i++)
			for (int j = 0; j < LogicHelper.LOGIC_MAXSIZE; j++)
				horizontalHintBoard.addView(horizontalHint[i][j],
						(i * LogicHelper.LOGIC_MAXSIZE) + j);

		for (int i = 0; i < LogicHelper.LOGIC_MAXSIZE; i++) {
			verticalHintCheck(new Point(i, i));
			horizontalHintCheck(new Point(i, i));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_logic, menu);
		return true;
	}

	public static void setUseItem(item selectItem) {
		useItem = selectItem;

		if (useItem == item.SHOW) {
			itemBox.setImageResource(R.drawable.item_showimage);
			showImage();
		} else {
			switch (useItem) {
			case VERTICAL:
				Toast.makeText(context, "원하는 범위를 선택하세요",
						Toast.LENGTH_SHORT).show();
				itemBox.setImageResource(R.drawable.item_vertical);
				break;
			case HORIZONTAL:
				Toast.makeText(context, "원하는 범위를 선택하세요",
						Toast.LENGTH_SHORT).show();
				itemBox.setImageResource(R.drawable.item_horizontal);
				break;
			case SQUAR:
				Toast.makeText(context, "원하는 범위를 선택하세요",
						Toast.LENGTH_SHORT).show();
				itemBox.setImageResource(R.drawable.item_squar);
				break;
			case REMOVE:
				Toast.makeText(context, "지우실 엑스를 선택하세요",
						Toast.LENGTH_SHORT).show();
				itemBox.setImageResource(R.drawable.item_removex);
				break;
			}
			moveFlag = false;
			moveBtn.setImageResource(R.drawable.move_button);
			editBtn.setImageResource(R.drawable.edit_button_touched);
		}
	}

	private static void showImage() {
		for (int i = 0; i < LogicHelper.LOGIC_MAXSIZE; i++) {
			for (int j = 0; j < LogicHelper.LOGIC_MAXSIZE; j++) {
				if (logicValue[i][j] == 1)
					tile[i][j].setImageResource(R.drawable.black_tile);
				else
					tile[i][j].setImageResource(R.drawable.black_x_tile);

			}
		}

		Handler mHandler = new Handler();
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				logicState = changeLogic.getDbState(section.x, section.y);
				for (int i = 0; i < LogicHelper.LOGIC_MAXSIZE; i++) {
					for (int j = 0; j < LogicHelper.LOGIC_MAXSIZE; j++) {
						if (logicState[i][j] == 0) {
							tile[i][j].setImageResource(R.drawable.white_tile);
							tile[i][j].setContentDescription("BLANK");
						} else if (logicState[i][j] == 1) {
							tile[i][j]
									.setImageResource(R.drawable.black_x_tile);
							tile[i][j].setContentDescription("CHECK");
						} else if (logicState[i][j] == 2) {
							tile[i][j].setImageResource(R.drawable.red_x_tile);
							tile[i][j].setContentDescription("FAIL");
						} else {
							tile[i][j].setImageResource(R.drawable.black_tile);
							tile[i][j].setContentDescription("SUCCESS");
						}
					}
				}
				useItem = item.NONE;
				LogicHelper.accountInfo.changeShowImage(-1);
				itemBox.setImageResource(R.drawable.item_none);
			}
		}, 3000);

	}

	private static void finishSection() {
		timer.stop();
		zoomToSmall();
		SectionCloseImageDialog sciDialog;
		if (successCount == numOfSuccess)
			sciDialog = new SectionCloseImageDialog(context,
					R.drawable.section_success);
		else
			sciDialog = new SectionCloseImageDialog(context,
					R.drawable.section_fail);
		sciDialog.getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		sciDialog.setCanceledOnTouchOutside(false);
		sciDialog.getWindow().setBackgroundDrawable(
				new ColorDrawable(android.graphics.Color.TRANSPARENT));
		sciDialog.show();
	}

	private static boolean changeTile(Point location,
			LogicHelper.tileState changeState) {
		String state = tile[location.x][location.y].getContentDescription()
				.toString();
		switch (changeState) {
		case CANCLE:
			if (state.equals("BLANK"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.white_tile);
			else if (state.equals("CHECK"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.black_x_tile);
			else if (state.equals("SUCCESS"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.black_tile);
			else if (state.equals("FAIL")) {
				if (useItem == item.REMOVE) {
					tile[location.x][location.y]
							.setImageResource(R.drawable.black_x_tile);
					tile[location.x][location.y].setContentDescription("CHECK");
					logicState[location.x][location.y] = 1;
					failCount--;
					checkFail();
					byte[] temp = { 1 };
					LogicHelper.db.setState(LogicHelper.logicInfo.getName(),
							new Point(section.y * 25 + location.y, section.x
									* 25 + location.x), new Point(section.y
									* 25 + location.y + 0, section.x * 25
									+ location.x), temp);
				} else
					tile[location.x][location.y]
							.setImageResource(R.drawable.red_x_tile);
			}
			break;

		case CHECK:
			if (state.equals("BLANK")) {
				tile[location.x][location.y]
						.setImageResource(R.drawable.black_x_tile);
				tile[location.x][location.y].setContentDescription("CHECK");
				logicState[location.x][location.y] = 1;
			} else if (state.equals("CHECK")) {
				tile[location.x][location.y]
						.setImageResource(R.drawable.black_x_tile);
			} else if (state.equals("SUCCESS"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.black_tile);
			else if (state.equals("FAIL"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.red_x_tile);
			horizontalHintCheck(location);
			verticalHintCheck(location);
			break;
		case DELETE:
			if (state.equals("BLANK"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.white_tile);
			else if (state.equals("CHECK")) {
				tile[location.x][location.y]
						.setImageResource(R.drawable.white_tile);
				tile[location.x][location.y].setContentDescription("BLANK");
				logicState[location.x][location.y] = 0;
			} else if (state.equals("SUCCESS"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.black_tile);
			else if (state.equals("FAIL"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.red_x_tile);
			horizontalHintCheck(location);
			verticalHintCheck(location);
			break;
		case DRAG:
			if (state.equals("BLANK"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.dwhite_tile);
			else if (state.equals("CHECK"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.dblack_x_tile);
			else if (state.equals("SUCCESS"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.dblack_tile);
			else if (state.equals("FAIL"))
				tile[location.x][location.y]
						.setImageResource(R.drawable.dred_x_tile);
			break;
		case DECISION:
			if (state.equals("CHECK") && !firstTouchInCheck) {
				tile[location.x][location.y]
						.setImageResource(R.drawable.black_x_tile);
				horizontalHintCheck(location);
				verticalHintCheck(location);
			} else if (logicValue[location.x][location.y] == 1) {
				tile[location.x][location.y]
						.setImageResource(R.drawable.black_tile);
				tile[location.x][location.y].setContentDescription("SUCCESS");
				logicState[location.x][location.y] = 3;
				if (!state.equals("SUCCESS"))
					successCount++;
				horizontalHintCheck(location);
				verticalHintCheck(location);
			} else {
				tile[location.x][location.y]
						.setImageResource(R.drawable.red_x_tile);
				tile[location.x][location.y].setContentDescription("FAIL");
				logicState[location.x][location.y] = 2;
				if (!state.equals("FAIL"))
					failCount++;
				horizontalHintCheck(location);
				verticalHintCheck(location);
				return false;
			}
			break;
		case ITEM:
			if (state.equals("FAIL")) {
				tile[location.x][location.y]
						.setImageResource(R.drawable.red_x_tile);
			} else {
				if (logicValue[location.x][location.y] == 1) {
					tile[location.x][location.y]
							.setImageResource(R.drawable.black_tile);
					tile[location.x][location.y]
							.setContentDescription("SUCCESS");
					logicState[location.x][location.y] = 3;
					if (!state.equals("SUCCESS"))
						successCount++;

				} else {
					tile[location.x][location.y]
							.setImageResource(R.drawable.black_x_tile);
					tile[location.x][location.y].setContentDescription("CHECK");
					logicState[location.x][location.y] = 1;
				}
			}
			horizontalHintCheck(location);
			verticalHintCheck(location);
			break;
		}
		return true;
	}

	private static void horizontalHintCheck(Point location) {
		int row, index = 0;
		for (row = 0; row < horizontalHintSize; row++) {
			if (!horizontalHint[row][location.y].getText().equals(" ")) {
				if (horizontalHint[row][location.y].getText().equals("0"))
					return;
				index = row;
				break;
			}
		}

		int blackCount = 0;
		for (row = 0; row < LogicHelper.LOGIC_MAXSIZE; row++) {
			CharSequence tileState = tile[row][location.y]
					.getContentDescription();
			if (tileState.equals("SUCCESS")) {
				blackCount++;
				if (blackCount == LogicHelper.LOGIC_MAXSIZE)
					index++;
			} else if (tileState.equals("FAIL") || tileState.equals("CHECK")) {
				if (blackCount != 0) {
					if (Integer.parseInt(horizontalHint[index][location.y]
							.getText().toString()) == blackCount)
						index++;
					else
						break;
				}
				blackCount = 0;
			} else
				break;
		}

		for (row = 0; row < horizontalHintSize; row++) {
			if (row < index) {
				horizontalHint[row][location.y].setTextColor(Color.RED);
			} else {
				horizontalHint[row][location.y].setTextColor(Color.BLACK);
			}
		}

		for (row = horizontalHintSize - 1; row >= 0; row--) {
			if (!horizontalHint[row][location.y].getText().equals(" ")) {
				if (horizontalHint[row][location.y].getText().equals("0"))
					return;
				index = row;
				break;
			}
		}
		blackCount = 0;
		for (row = LogicHelper.LOGIC_MAXSIZE - 1; row >= 0; row--) {
			CharSequence tileState = tile[row][location.y]
					.getContentDescription();
			if (tileState.equals("SUCCESS")) {
				blackCount++;
				if (blackCount == LogicHelper.LOGIC_MAXSIZE)
					index++;
			} else if (tileState.equals("FAIL") || tileState.equals("CHECK")) {
				if (blackCount != 0) {
					if (Integer.parseInt(horizontalHint[index][location.y]
							.getText().toString()) == blackCount)
						index--;
					else
						break;
				}
				blackCount = 0;
			} else
				break;
		}

		for (row = horizontalHintSize - 1; row > index; row--)
			horizontalHint[row][location.y].setTextColor(Color.RED);
	}

	private static void verticalHintCheck(Point location) {
		int col, index = 0;
		for (col = 0; col < verticalHintSize; col++) {
			if (!verticalHint[location.x][col].getText().equals(" ")) {
				if (verticalHint[location.x][col].getText().equals("0"))
					return;
				index = col;
				break;
			}
		}

		int blackCount = 0;
		for (col = 0; col < LogicHelper.LOGIC_MAXSIZE; col++) {
			CharSequence tileState = tile[location.x][col]
					.getContentDescription();
			if (tileState.equals("SUCCESS")) {
				blackCount++;
				if (blackCount == LogicHelper.LOGIC_MAXSIZE)
					index++;
			} else if (tileState.equals("FAIL") || tileState.equals("CHECK")) {
				if (blackCount != 0) {
					if (Integer.parseInt(verticalHint[location.x][index]
							.getText().toString()) == blackCount)
						index++;
					else
						break;
				}
				blackCount = 0;
			} else
				break;
		}

		for (col = 0; col < verticalHintSize; col++) {
			if (col < index) {
				verticalHint[location.x][col].setTextColor(Color.RED);
			} else {
				verticalHint[location.x][col].setTextColor(Color.BLACK);
			}
		}

		for (col = verticalHintSize - 1; col >= 0; col--) {
			if (!verticalHint[location.x][col].getText().equals(" ")) {
				if (verticalHint[location.x][col].getText().equals("0"))
					return;
				index = col;
				break;
			}
		}
		blackCount = 0;
		for (col = LogicHelper.LOGIC_MAXSIZE - 1; col >= 0; col--) {
			CharSequence tileState = tile[location.x][col]
					.getContentDescription();
			if (tileState.equals("SUCCESS")) {
				blackCount++;
				if (blackCount == LogicHelper.LOGIC_MAXSIZE)
					index++;
			} else if (tileState.equals("FAIL") || tileState.equals("CHECK")) {
				if (blackCount != 0) {
					if (Integer.parseInt(verticalHint[location.x][index]
							.getText().toString()) == blackCount)
						index--;
					else
						break;
				}
				blackCount = 0;
			} else
				break;
		}

		for (col = verticalHintSize - 1; col > index; col--)
			verticalHint[location.x][col].setTextColor(Color.RED);
	}

	public static void changeHorizontalTile(Point base, int length,
			tileState changeState, boolean saveSate) {
		Log.i(TAG, "dir is HORIZONTAL");
		Log.i(TAG, "base(x,y) is (" + base.x + "," + base.y + ") length is "
				+ length);
		int i, count;
		Point location;
		byte[] changelist;

		if (base.x < 0 || base.x >= LogicHelper.LOGIC_MAXSIZE || base.y < 0
				|| base.y >= LogicHelper.LOGIC_MAXSIZE)
			return;

		// drag가 로직을 벗어날 경우
		if (length > 0) {
			if (base.x + length >= LogicHelper.LOGIC_MAXSIZE)
				length = LogicHelper.LOGIC_MAXSIZE - base.x - 1;
			i = base.x - 1;
			count = -1;
		} else {
			if (base.x + length < 0)
				length = -base.x;
			i = base.x + 1;
			count = Math.abs(length) + 1;
		}

		if (logicState[base.y][base.x] == 1 && changeState == tileState.CHECK)
			changeState = tileState.DELETE;

		firstTouchInCheck = false;
		if (logicState[base.y][base.x] == 1
				&& changeState == tileState.DECISION)
			firstTouchInCheck = true;

		changelist = new byte[Math.abs(length) + 1];
		boolean fail = false;
		while (true) {
			if (length > 0) {
				if (i >= base.x + length)
					break;
				i++;
				count++;
			} else {
				if (i <= base.x + length)
					break;
				i--;
				count--;
			}
			location = new Point(base.y, i);
			if (!fail) {
				if (!changeTile(location, changeState))
					fail = true;
				changelist[count] = logicState[location.x][location.y];
			} else {
				changeTile(location, tileState.CANCLE);
				changelist[count] = logicState[location.x][location.y];
			}
		}
		if (!fail && changeState == tileState.DECISION) {
			if ((int) (Math.random() * LUCKY_PERCENT) == 0) {
				GiveCoinDialog coinDialog = new GiveCoinDialog(context,
						coinGiveType.LUCKY);
				coinDialog.getWindow().clearFlags(
						WindowManager.LayoutParams.FLAG_DIM_BEHIND);
				coinDialog.show();
			}
		}
		if (saveSate) {
			Log.i(TAG, "successCount is" + successCount);
			Log.i(TAG, "numOfSuccess is" + numOfSuccess);
			if (successCount == numOfSuccess)
				finishSection();
			if (changeState != tileState.CANCLE
					&& changeState != tileState.DRAG) {
				LogicHelper.db.setState(LogicHelper.logicInfo.getName(),
						new Point(section.y * 25 + base.x, section.x * 25
								+ base.y), new Point(section.y * 25 + base.x
								+ length, section.x * 25 + base.y), changelist);
				LogicHelper.db
						.setCompleteness(
								LogicHelper.logicInfo.getName(),
								new Point(section.x, section.y),
								(int) (((float) successCount / (float) numOfSuccess) * 100));
				long elapsedMillis = SystemClock.elapsedRealtime()
						- timer.getBase();
				LogicHelper.db.setTime(LogicHelper.logicInfo.getName(),
						elapsedMillis);
				Log.i(TAG, elapsedMillis / 1000 + "is saved Time~~!");
			}
			checkFail();
		}
	}

	public static void changeVerticalTile(Point base, int length,
			tileState changeState, boolean saveSate) {
		Log.i(TAG, "dir is VERTICAL");
		Log.i(TAG, "base(x,y) is (" + base.x + "," + base.y + ") length is "
				+ length);
		int i, count;
		Point location;
		byte[] changelist;

		// Logic 밖에서 터치해 들어올 경우
		if (base.x < 0 || base.x >= LogicHelper.LOGIC_MAXSIZE || base.y < 0
				|| base.y >= LogicHelper.LOGIC_MAXSIZE)
			return;

		if (length > 0) {
			if (base.y + length >= LogicHelper.LOGIC_MAXSIZE)
				length = LogicHelper.LOGIC_MAXSIZE - base.y - 1;
			i = base.y - 1;
			count = -1;
		} else {
			if (base.y + length < 0)
				length = -base.y;
			i = base.y + 1;
			count = Math.abs(length) + 1;
		}

		if (logicState[base.y][base.x] == 1 && changeState == tileState.CHECK)
			changeState = tileState.DELETE;

		firstTouchInCheck = false;
		if (logicState[base.y][base.x] == 1
				&& changeState == tileState.DECISION)
			firstTouchInCheck = true;

		changelist = new byte[Math.abs(length) + 1];
		boolean fail = false;

		while (true) {
			if (length > 0) {
				if (i >= base.y + length)
					break;
				i++;
				count++;
			} else {
				if (i <= base.y + length)
					break;
				i--;
				count--;
			}
			location = new Point(i, base.x);
			if (!fail) {
				if (!changeTile(location, changeState))
					fail = true;
				changelist[count] = logicState[location.x][location.y];
			} else {
				changeTile(location, tileState.CANCLE);
				changelist[count] = logicState[location.x][location.y];
			}
		}
		if (!fail && changeState == tileState.DECISION) {
			if ((int) (Math.random() * LUCKY_PERCENT) == 0) {
				GiveCoinDialog coinDialog = new GiveCoinDialog(context,
						coinGiveType.LUCKY);
				coinDialog.getWindow().clearFlags(
						WindowManager.LayoutParams.FLAG_DIM_BEHIND);
				coinDialog.show();
			}
		}
		if (saveSate) {
			Log.i(TAG, "successCount is" + successCount);
			Log.i(TAG, "numOfSuccess is" + numOfSuccess);
			if (successCount == numOfSuccess)
				finishSection();

			if (changeState != tileState.CANCLE
					&& changeState != tileState.DRAG) {
				LogicHelper.db.setState(LogicHelper.logicInfo.getName(),
						new Point(section.y * 25 + base.x, section.x * 25
								+ base.y), new Point(section.y * 25 + base.x,
								section.x * 25 + base.y + length), changelist);
				LogicHelper.db
						.setCompleteness(
								LogicHelper.logicInfo.getName(),
								new Point(section.x, section.y),
								(int) (((float) successCount / (float) numOfSuccess) * 100));
				long elapsedMillis = SystemClock.elapsedRealtime()
						- timer.getBase();
				LogicHelper.db.setTime(LogicHelper.logicInfo.getName(),
						elapsedMillis);
				Log.i(TAG, elapsedMillis / 1000 + "is saved Time~~!");
			}
			checkFail();
		}
	}

	private static void changeSquarTile(Point point, tileState changeState,
			boolean saveSate) {
		for (int i = 0; i < 5; i++)
			changeVerticalTile(new Point(point.x * 5 + i, point.y * 5), 4,
					changeState, saveSate);
	}

	public static void setDialogOpen(boolean Open) {
		dialogOpen = Open;
	}

	private static void scroll(final int x, final int y) {
		boolean scrollToOutside = false;
		int changedX, changedY;
		changedX = horizontalScroll.getScrollX() + x;
		changedY = verticalScroll.getScrollY() + y;

		if (horizontalScroll.getScrollX() + x > (logicBoard.getWidth()) * scale
				- lcdWidth + verticalHintImage.getWidth()) {
			changedX = (int) ((logicBoard.getWidth()) * scale - lcdWidth + verticalHintImage
					.getWidth());
			scrollToOutside = true;
		}
		if (verticalScroll.getScrollY() + y > logicBoard.getHeight() * scale
				- logicFrame.getHeight()) {
			changedY = (int) (logicBoard.getHeight() * scale - logicFrame
					.getHeight());
			scrollToOutside = true;
		}

		if (scrollToOutside) {
			Log.i(TAG, "Scroll To Outside!");
			scrollTo(changedX, changedY);

		} else {
			Log.i(TAG, "Scroll by " + x + ", " + y);
			horizontalDivideTileScroll.scrollBy(x, y);
			verticalDivideTileScroll.scrollBy(x, y);
			horizontalHintScroll.scrollBy(x, y);
			verticalHintScroll.scrollBy(x, y);
			horizontalScroll.scrollBy(x, y);
			verticalScroll.scrollBy(x, y);
		}
		verticalHintMove();
	}

	private static void scrollTo(int x, int y) {
		horizontalDivideTileScroll.scrollTo(x, y);
		verticalDivideTileScroll.scrollTo(x, y);
		horizontalHintScroll.scrollTo(x, y);
		verticalHintScroll.scrollTo(x, y);
		horizontalScroll.scrollTo(x, y);
		verticalScroll.scrollTo(x, y);
	}

	private static void verticalHintMove() {
		for (int i = verticalHintSize - 1; i >= 0; i--) {
			if (horizontalScroll.getScrollX() / (tile[1][1].getWidth() * scale) >= i) {

				for (int row = 0; row < LogicHelper.LOGIC_MAXSIZE; row++) {
					int moveCount = i;
					if (Integer.parseInt(verticalHint[row][0]
							.getContentDescription().toString()) < i)
						moveCount = Integer.parseInt(verticalHint[row][0]
								.getContentDescription().toString());

					for (int col = 0; col < verticalHintSize; col++) {
						if ((col + moveCount) >= verticalHintSize)
							verticalHint[row][col]
									.setText((CharSequence) verticalHint[row][col
											+ moveCount - verticalHintSize]
											.getTag());
						else
							verticalHint[row][col]
									.setText((CharSequence) verticalHint[row][col
											+ moveCount].getTag());
					}
					verticalHintCheck(new Point(row, 0));
				}
				break;
			}
		}
	}

	private static void zoom(Float zoomScale) {
		// 줌하기 이전에 최대, 최소비율이 넘어 있으면 동작X
		if ((scale > (float) lcdWidth / logicBoard.getWidth()) || zoomScale < 0) {
			if (scale < 1 || zoomScale > 0) {
				setPivot();

				// 줌을 하고 나서 최대, 최소 비율이 넘을것 같을 경우 수정된 동작 실행
				if (scale - zoomScale < (float) lcdWidth
						/ (logicBoard.getWidth())) {
					setScale((float) lcdWidth / (logicBoard.getWidth()));
				} else if (scale - zoomScale > 1) {
					setScale((float) 1);
				} else {
					setScale(scale - zoomScale);
				}
			}
		}

		scale = logicBoard.getScaleX();
		Log.i(TAG, "Scale is " + scale);

		LinearLayout.LayoutParams plControl = (LinearLayout.LayoutParams) verticalHintImage
				.getLayoutParams();
		plControl.width = (int) (verticalHintWidth * scale);
		verticalHintImage.setLayoutParams(plControl);

		plControl = (LinearLayout.LayoutParams) mapView.getLayoutParams();
		plControl.width = (int) (verticalHintWidth * scale);
		mapView.setLayoutParams(plControl);

		scroll(0, 0);
	}

	public static void zoomToSmall() {
		scrollTo(0, 0);
		zoom(scale - (float) lcdWidth / (logicBoard.getWidth()));
		scroll((int) (verticalHintWidth * scale), 0);
	}

	private static void setPivot() {
		verticalDivideTile.setPivotX(verticalDivideTile.getWidth());
		verticalDivideTile.setPivotY(1);
		horizontalDivideTile.setPivotX(1);
		horizontalDivideTile.setPivotY(1);
		logicBoard.setPivotX(1);
		logicBoard.setPivotY(1);
		verticalHintBoard.setPivotX(1);
		verticalHintBoard.setPivotY(1);
		horizontalHintBoard.setPivotX(1);
		horizontalHintBoard.setPivotY(horizontalHintBoard.getHeight());
	}

	private static void setScale(Float scale) {
		verticalDivideTile.setScaleX(scale);
		verticalDivideTile.setScaleY(scale);
		horizontalDivideTile.setScaleX(scale);
		horizontalDivideTile.setScaleY(scale);
		logicBoard.setScaleX(scale);
		logicBoard.setScaleY(scale);
		verticalHintBoard.setScaleX(scale);
		verticalHintBoard.setScaleY(scale);
		horizontalHintBoard.setScaleX(scale);
		horizontalHintBoard.setScaleY(scale);
	}

	private Point getTouchedSquar(Point point) {
		Point squarPoint = new Point(point.x / 5, point.y / 5);
		return squarPoint;
	}

	private Point getTouchedTile(PointF rawPoint) {
		Point tilePoint = new Point();
		int tileBundleLength = 0, i;
		for (i = 5; i < 10; i++)
			tileBundleLength += tile[0][i].getWidth() * scale;

		rawPoint.x += horizontalScroll.getScrollX()
				- verticalHintImage.getWidth() - 3;
		rawPoint.y += verticalScroll.getScrollY()
				- horizontalHintBoard.getHeight() - logicInfoBoard.getHeight()
				- 3;
		Log.i(TAG, "rawPoint x = " + rawPoint.x + ", y = " + rawPoint.y);

		int bundleCount = (int) (Math.abs(rawPoint.x) / tileBundleLength);
		int restLength = (int) (Math.abs(rawPoint.x) % tileBundleLength);
		int tileCount = 0;
		int temp = 0;
		for (i = 0; i < 5; i++) {
			temp += tile[5][i].getWidth() * scale;
			if (restLength < temp)
				break;
		}
		tileCount = i;
		if (rawPoint.x >= 0)
			tilePoint.x = bundleCount * 5 + tileCount;
		else
			tilePoint.x = -1 * (bundleCount * 5 + tileCount);

		bundleCount = (int) (Math.abs(rawPoint.y) / tileBundleLength);
		restLength = (int) (Math.abs(rawPoint.y) % tileBundleLength);
		tileCount = 0;
		temp = 0;
		for (i = 0; i < 5; i++) {
			temp += tile[i][5].getHeight() * scale;
			if (restLength < temp)
				break;
		}
		tileCount = i;
		if (rawPoint.y >= 0)
			tilePoint.y = bundleCount * 5 + tileCount;
		else
			tilePoint.y = -1 * (bundleCount * 5 + tileCount);
		return tilePoint;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (useItem == item.SHOW)
			return true;
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			Log.i(TAG, "getY in onCreate is " + itemBox.getY());
			if (moveFlag)
				current.set((int) event.getX(), (int) event.getY());
			else if (!dialogOpen) {
				first.set(event.getRawX(), event.getRawY());
				Log.i(TAG, "first x is " + first.x + ", y is " + first.y);
				drag = getTouchedTile(first);
				first.set(event.getRawX(), event.getRawY());

				if (useItem == item.NONE || useItem == item.REMOVE) {
					if (drag.x >= 0 && drag.x < LogicHelper.LOGIC_MAXSIZE
							&& drag.y >= 0
							&& drag.y < LogicHelper.LOGIC_MAXSIZE) {
						dragCount = 0;
						changeHorizontalTile(drag, 0,
								LogicHelper.tileState.DRAG, false);

					}
				} else if (useItem == item.VERTICAL) {
					drag.y = 0;
					if (drag.x >= 0 && drag.x < LogicHelper.LOGIC_MAXSIZE) {
						dragCount = 0;
						changeVerticalTile(drag, LogicHelper.LOGIC_MAXSIZE - 1,
								LogicHelper.tileState.DRAG, false);

					}

				} else if (useItem == item.HORIZONTAL) {
					drag.x = 0;
					if (drag.y >= 0 && drag.y < LogicHelper.LOGIC_MAXSIZE) {
						dragCount = 0;
						changeHorizontalTile(drag,
								LogicHelper.LOGIC_MAXSIZE - 1,
								LogicHelper.tileState.DRAG, false);

					}

				} else if (useItem == item.SQUAR) {
					dragCount = 0;
					if (drag.x >= 0 && drag.x < LogicHelper.LOGIC_MAXSIZE
							&& drag.y >= 0
							&& drag.y < LogicHelper.LOGIC_MAXSIZE) {
						squar = getTouchedSquar(drag);
						changeSquarTile(squar, tileState.DRAG, false);
					}
				}
			}
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			break;
		case MotionEvent.ACTION_MOVE:
			if (moveFlag) {
				if (event.getPointerCount() > 1) {
					presentDistance = (float) Math.sqrt(Math.pow(event.getX(0)
							- event.getX(1), 2)
							+ Math.pow(event.getY(0) - event.getY(1), 2));
					if (previousDistance == 0) {
						previousDistance = presentDistance;
					}
					Log.i(TAG, "previousDistance is	" + previousDistance);
					Log.i(TAG, "presentDistance is " + presentDistance);
					zoom((previousDistance - presentDistance) / 1000);
					previousDistance = presentDistance;
				} else {
					int x2 = (int) event.getX();
					int y2 = (int) event.getY();
					scroll(current.x - x2, current.y - y2);
					current.set(x2, y2);
				}
			} else if (!dialogOpen) {
				if (useItem == item.NONE) {
					if (dragCount != 0) {
						if (dir == LogicHelper.dragStyle.HORIZONTAL)
							changeHorizontalTile(drag, dragCount,
									LogicHelper.tileState.CANCLE, false);
						else
							changeVerticalTile(drag, dragCount,
									LogicHelper.tileState.CANCLE, false);
					}
					float Xdistance, Ydistance;
					Xdistance = event.getRawX() - first.x;
					Ydistance = event.getRawY() - first.y;
					if (Math.abs(Xdistance) > Math.abs(Ydistance)
							&& Math.abs(Xdistance) >= (tile[1][1].getWidth() * scale)) {
						dir = LogicHelper.dragStyle.HORIZONTAL;
						dragCount = (int) (Xdistance / (tile[1][1].getWidth() * scale));
						changeHorizontalTile(drag, dragCount,
								LogicHelper.tileState.DRAG, false);
					} else if (Math.abs(Ydistance) > Math.abs(Xdistance)
							&& Math.abs(Ydistance) >= (tile[1][1].getHeight() * scale)) {
						dir = LogicHelper.dragStyle.VERTICAL;
						dragCount = (int) (Ydistance / (tile[1][1].getHeight() * scale));
						changeVerticalTile(drag, dragCount,
								LogicHelper.tileState.DRAG, false);
					}

				} else if (useItem == item.VERTICAL) {
					changeVerticalTile(new Point(drag.x + dragCount, 0),
							LogicHelper.LOGIC_MAXSIZE - 1,
							LogicHelper.tileState.CANCLE, false);
					float Xdistance;
					Xdistance = event.getRawX() - first.x;
					dragCount = (int) (Xdistance / (tile[1][1].getWidth() * scale));
					changeVerticalTile(new Point(drag.x + dragCount, 0),
							LogicHelper.LOGIC_MAXSIZE - 1,
							LogicHelper.tileState.DRAG, false);

				} else if (useItem == item.HORIZONTAL) {
					changeHorizontalTile(new Point(0, drag.y + dragCount),
							LogicHelper.LOGIC_MAXSIZE - 1,
							LogicHelper.tileState.CANCLE, false);
					float Ydistance;
					Ydistance = event.getRawY() - first.y;
					dragCount = (int) (Ydistance / (tile[1][1].getWidth() * scale));
					changeHorizontalTile(new Point(0, drag.y + dragCount),
							LogicHelper.LOGIC_MAXSIZE - 1,
							LogicHelper.tileState.DRAG, false);

				} else if (useItem == item.SQUAR) {
					changeSquarTile(squar, tileState.CANCLE, false);

					first.set(event.getRawX(), event.getRawY());
					drag = getTouchedTile(first);

					squar = getTouchedSquar(new Point(drag.x, drag.y));
					changeSquarTile(squar, tileState.DRAG, false);

				} else if (useItem == item.REMOVE) {
					changeHorizontalTile(drag, 0, LogicHelper.tileState.CANCLE,
							false);

					first.set(event.getRawX(), event.getRawY());
					drag = getTouchedTile(first);

					changeHorizontalTile(drag, 0, LogicHelper.tileState.DRAG,
							false);
				}
			}
			break;
		case MotionEvent.ACTION_UP:
			if (moveFlag) {
				previousDistance = 0;
			} else if (!dialogOpen) {
				if (useItem == item.NONE) {
					if (drag.x >= 0 && drag.x < LogicHelper.LOGIC_MAXSIZE
							&& drag.y >= 0
							&& drag.y < LogicHelper.LOGIC_MAXSIZE) {
						TileSelectDialog dialog = new TileSelectDialog(this,
								dir, drag, dragCount);
						dialog.getWindow().clearFlags(
								WindowManager.LayoutParams.FLAG_DIM_BEHIND);

						dialog.setOnCancelListener(new OnCancelListener() {
							@Override
							public void onCancel(DialogInterface dialog) {
								if (dir == LogicHelper.dragStyle.HORIZONTAL)
									changeHorizontalTile(drag, dragCount,
											LogicHelper.tileState.CANCLE, true);
								else
									changeVerticalTile(drag, dragCount,
											LogicHelper.tileState.CANCLE, true);
								dialogOpen = false;
							}
						});

						WindowManager.LayoutParams params = dialog.getWindow()
								.getAttributes();
						params.x = (int) first.x + params.width / 2 - lcdWidth
								/ 2;
						params.y = (int) (first.y + params.height / 2
								- lcdHeight / 2 - tile[0][0].getHeight() * 2);
						dialog.getWindow().setAttributes(params);

						dialogOpen = true;
						dialog.show();
					}

				} else if (useItem == item.VERTICAL) {
					if ((drag.x + dragCount) >= 0 && (drag.x + dragCount) < 25) {
						changeVerticalTile(new Point(drag.x + dragCount, 0),
								LogicHelper.LOGIC_MAXSIZE - 1,
								LogicHelper.tileState.ITEM, true);
						LogicHelper.accountInfo.changeVertical(-1);
						useItem = item.NONE;
						itemBox.setImageResource(R.drawable.item_none);
					}

				} else if (useItem == item.HORIZONTAL) {
					if ((drag.y + dragCount) >= 0 && (drag.y + dragCount) < 25) {
						changeHorizontalTile(new Point(0, drag.y + dragCount),
								LogicHelper.LOGIC_MAXSIZE - 1,
								LogicHelper.tileState.ITEM, true);
						LogicHelper.accountInfo.changeHorizontal(-1);
						useItem = item.NONE;
						itemBox.setImageResource(R.drawable.item_none);
					}

				} else if (useItem == item.SQUAR) {
					if (squar.x >= 0 && squar.x < 5 && squar.y >= 0
							&& squar.y < 5) {
						changeSquarTile(squar, tileState.ITEM, true);
						LogicHelper.accountInfo.changeSquar(-1);
						useItem = item.NONE;
						itemBox.setImageResource(R.drawable.item_none);
					}
				} else if (useItem == item.REMOVE) {
					if (drag.x >= 0 && drag.x < LogicHelper.LOGIC_MAXSIZE
							&& drag.y >= 0
							&& drag.y < LogicHelper.LOGIC_MAXSIZE) {

						changeHorizontalTile(drag, 0,
								LogicHelper.tileState.CANCLE, false);
						LogicHelper.accountInfo.changeRemoveX(-1);
						useItem = item.NONE;
						itemBox.setImageResource(R.drawable.item_none);
					}
				}
			}
			break;
		case MotionEvent.ACTION_POINTER_UP:
			break;
		default:

			if (moveFlag) {
				current.x = (int) event.getX();
				current.y = (int) event.getY();
				Log.e(TAG, current.x + "," + current.y);
			}
			break;
		}
		current.set((int) event.getX(), (int) event.getY());
		return true;
	}

	@Override
	protected void onPause() {
		Log.i(TAG, "pause");
		long elapsedMillis = SystemClock.elapsedRealtime() - timer.getBase();
		LogicHelper.db.setTime(LogicHelper.logicInfo.getName(), elapsedMillis);
		LogicHelper.backgroundMusic.onPause(getApplicationContext());
		super.onPause();
	}

	@Override
	protected void onResume() {
		Log.i(TAG, "resumes");
		Basetime = LogicHelper.db.getTime(LogicHelper.logicInfo.getName());
		timer.setBase(SystemClock.elapsedRealtime() - Basetime);
		timer.start();
		LogicHelper.backgroundMusic.onStart();
		super.onResume();
	}

	@Override
	public void onBackPressed() {
		long elapsedMillis = SystemClock.elapsedRealtime() - timer.getBase();
		LogicHelper.db.setTime(LogicHelper.logicInfo.getName(), elapsedMillis);
		Log.i(TAG, elapsedMillis / 1000 + "is saved Time~~!");
		Intent it = new Intent(LogicActivity.this, SelectSectionActivity.class);
		it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(it);
		finish();
	}
}
